package com.ruoyi.system.aspectj;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.Article;
import com.ruoyi.system.domain.Comments;
import com.ruoyi.system.exception.CustomException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class ArticleParamsAspect {
    @Pointcut("@annotation(com.ruoyi.system.anotation.FillParams)")
    public void fill() {
    }

    @Before("fill()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        Object[] objects = joinPoint.getArgs();
        Arrays.stream(objects).forEach(item -> {
            if (item instanceof com.ruoyi.system.domain.Article) {
                Article article = (Article) item;
                if (article.getArticleContent() == null || article.getArticleTitle() == null) {
                    throw new CustomException("文章标题和内容不能为空");
                } else {
                    article.setArticleViews(0L);
                    article.setArticleLikes(0L);
                    article.setArticleDate(new Date());
                }
            } else if (item instanceof com.ruoyi.system.domain.Comments) {
                Comments comment = (Comments) item;
                if (comment.getCommentContent() == null ) {
                    throw new CustomException("评论内容不能为空!");
                } else {
                    comment.setCommentDate(new Date());
                    comment.setCommentPublisher(SecurityUtils.getLoginUser().getUser().getNickName());
                    comment.setCommentLikes(0L);
                }
            }
        });
    }
}
